package concroller;
import domain.Fruit;

import java.io.*;
import java.net.Socket;
import java.util.ResourceBundle;
import java.util.Scanner;

public class FruitController {
    Scanner sc = new Scanner(System.in);
    //FruitService service = new FruitService();
    // ArrayList<Fruit> list = service.findAllFruits();
    Socket socket = getSocket();
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    public FruitController() throws IOException {
    }

    //int[] arr = new int[list.size()];
    String markNum;

    public void start1() {
        System.out.println("请输入用户名:");
        String name = sc.next();
        System.out.println("请输入密码:");
        String passWord = sc.next();
        //设计通信的报文协议,此处[0]则代表管理员的登录请求,以"[0]" + name+","+passWord格式拼接数据
        String msg = "[0]" + name+","+passWord;
        try {
            bw.write(msg);
            bw.newLine();
            bw.flush();
            String res = br.readLine();
            if (res.equals("true")) {
                System.out.println("欢迎您:" + name);
                start2();
            } else {
                System.out.println("不要皮,你不是管理员!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void start2() throws IOException {
        loop:
        while (true) {
            System.out.println("请输入您的选择:(1.查看水果   2.添加水果   3.修改水果   4.删除水果   5.退出)");
            String choice = sc.next();
            switch (choice) {
                case "1":
                    managerCheck();
                    break;
                case "2":
                    add();
                    break;
                case "3":
                    update();
                    break;
                case "4":
                    delete();
                    break;
                case "5":
                    System.out.println("感谢您的使用~");
                    break loop;
                default:
                    break;
            }
        }
    }

    public void managerCheck() throws IOException {

        //service.managerCheck();
        Socket socket = getSocket();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write("[6]");
        bw.newLine();
        bw.flush();
        //socket.shutdownOutput();
        System.out.println("编号" + "\t\t\t" + "名称" + "\t\t" + "价格" + "\t\t" + "库存" + "\t\t" + "单位");
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        bw.close();
        br.close();
        socket.close();
    }

      public void update() {
          System.out.println("请输入要修改的水果编号:");
          //String num = sc.next();
          //boolean res = service.isExist(num);
          String num = inputFruittId(true);
          Fruit f = inputStudentInfo(num);
          try {
              Socket socket = getSocket();
              BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
              bw.write("[5]"+f.toString());
              bw.newLine();
              bw.flush();
              BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              String msg = br.readLine();
              boolean res = false;
              if (msg.equals("true")){
                  res = true;
              }
              //4. 根据业务员返回的结果,给出用户对应的提示信息
              if (res) {
                  System.out.println("修改成功");
              } else {
                  System.out.println("您输入的编号不存在,修改失败.请重新您的选择!");
              }
          } catch (IOException e) {
              e.printStackTrace();
          }
          /*if (res) {
              System.out.println("请输入要修改的水果名称:");
              String name = sc.next();
              System.out.println("请输入要修改的水果单价:");
              int price = sc.nextInt();
              System.out.println("请输入要修改的水果库存:");
              int inventory = sc.nextInt();
              System.out.println("请输入要修改的水果单位:");
              String unit = sc.next();
              Fruit newFruit = new Fruit(num, name, price, inventory, unit);
              System.out.println("修改成功!");
              System.out.println("修改后的信息如下:");
              System.out.println("编号" + "\t\t\t" + "名称" + "\t\t" + "价格" + "\t\t" + "库存" + "\t\t" + "单位");
              System.out.println(num + "\t\t" + name + "\t\t" + price + "\t\t\t" + inventory + "\t\t\t" + unit);
              service.update(num, newFruit);
          } else {
             // tips1();
          }*/
      }
   /* public void tips1() {
        System.out.println("您输入的编号不存在,修改失败!<温馨提示:是否需要添加新品?>");
        while (true) {
            System.out.println("Yes-->继续添加请按<1>         No-->返回上级菜单请按<0>");
            int choice = sc.nextInt();
            if (choice == 1) {
                add();
                break;
            } else if (choice == 0) {
                return;
            } else {
                System.out.println("您输入的信息有误,请按提示进行操作!");
            }
        }
    }
*/
    public void delete() {
        System.out.println("请输入要删除的水果编号:");
        String num = inputFruittId(true);
        //boolean res = service.isExist(num);
        /*if (res) {
            service.delete(num);
            System.out.println("删除成功!");
        } else {
            System.out.println("您输入的编号不存在,删除失败.请重新您的选择!");
        }*/
        try {
            Socket socket = getSocket();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("[4]"+num);
            bw.newLine();
            bw.flush();
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String msg = br.readLine();
            boolean res = false;
            if (msg.equals("true")){
                res = true;
            }
            //4. 根据业务员返回的结果,给出用户对应的提示信息
            if (res) {
                System.out.println("删除成功");
            } else {
                System.out.println("您输入的编号不存在,删除失败.请重新您的选择!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void add(){
        System.out.println("请输入要添加的水果编号:");
        String num = inputFruittId(false);

        Fruit f = inputStudentInfo(num);
        try {
            Socket socket = getSocket();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("[3]" + f.toString());
            bw.newLine();
            bw.flush();

            //4. 接收服务器返回的结果
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String msg = br.readLine();

            boolean res = false;
            if (msg.equals("true")){
                res = true;
            }
            //4. 根据业务员返回的结果,给出用户对应的提示信息
            if (res) {
                System.out.println("添加成功");
            } else {
                System.out.println("添加失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public Fruit inputStudentInfo(String id){
        System.out.println("请输入要添加的水果名称:");
        String name = sc.next();
        System.out.println("请输入要添加的水果单价:");
        int price = sc.nextInt();
        System.out.println("请输入要修改的水果库存:");
        int inventory = sc.nextInt();
        System.out.println("请输入要添加的水果单位:");
        String unit = sc.next();
        Fruit fru = new Fruit(id,name,price,inventory,unit);
        return fru;
    }

    public String inputFruittId(boolean flag){
        String id;
        try {
            while (true) {
                id = sc.next();
                //1. 获取socket对象
                Socket socket = getSocket();
                //2. 以"[1]id=heima001"格式拼接请求数据
                String msg = "[1]"+id;
                //3. 将数据发送给服务器
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                bw.write(msg);
                bw.newLine();
                bw.flush();

                //4. 接收服务器响应的结果数据
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String res = br.readLine();
                boolean exists = false;
                if (res.equals("true")){
                    exists = true;
                }

                if (exists == flag) {
                    break;
                } else {
                    System.out.println("当前编号不可用,请重新输入:");
                }
            }
            return id;

        }catch (Exception e){
            System.out.println("系统错误!");
            return null;
        }

    }

   /* public void tips2() {
        System.out.println("不好意思,您输入的水果编号已经存在了!<温馨提示:是否需要修改已有的商品?>");
        while (true) {
            System.out.println("Yes-->操作修改请按<1>                     No-->返回上级菜单请按<0>");
            int choice = sc.nextInt();
            if (choice == 1) {
                update();
                break;
            } else if (choice == 0) {
                return;
            } else {
                System.out.println("您输入的信息有误,请按提示进行操作!");
            }
        }
    }
*/

       public void open() {
           looop:
           while (true) {
               System.out.println("请输入您的选择:(1.查看水果   2.开始购买   3.结账   4.退出)");
               String choice = sc.next();
               switch (choice) {
                   case "1":
                       check();
                       break;
                   case "2":
//                       if ("1".equals(markNum)) {
//                           service.checkByPrice();
//                       } else {
//                           service.check();
//                       }
                      // buy();
                       break;
                   case "3":
                      // count();
                       break;
                   case "4":
                       System.out.println("欢迎您下次光临~");
                       break looop;
                   default:
                       break;
               }
           }
       }

    public void check() {
       // service.check();
        try {
            Socket socket = getSocket();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("[6]");
            bw.newLine();
            bw.flush();
            //socket.shutdownOutput();
            System.out.println("编号" + "\t\t\t" + "名称" + "\t\t" + "价格" + "\t\t" + "库存" + "\t\t" + "单位");
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

            System.out.println("当前系统默认以库存降序显示   您也可以选择以价格进行排序哦~");
            System.out.println("如需切换请按<1>                    返回上级菜单请按<0>");
            markNum = sc.next();
            switch (markNum) {
                case "1":
                    //service.checkByPrice();
                    return;
                case "0":
                    return;
                default:
                    System.err.println("您的输入有误,请按提示操作~");
                    break;
            }
            bw.close();
            br.close();
            socket.close();
        } catch (IOException e) {

        }
    }

   /* public void buy() {
        System.out.println("本店开业大酬宾,多买多优惠哦~");
        System.out.println("优惠规则如下:1.消费金额100元以内无优惠");
        System.out.println("            2.消费金额200元以内超出100的可以享受9折优惠");
        System.out.println("            3.消费金额500元以内超出100的不超出200的部分9折优惠,超出200低于500以内的8折优惠");
        System.out.println("            4.消费金额500以上的,500元以内优惠力度如上,500元以外的金额7折优惠");

        while (true) {
            System.out.println("请选择您要购买的水果(请输入对应的水果编号):");
            String fruitNum = sc.next();
            boolean exist = service.isExist(fruitNum);
            for (int i = 0; i < list.size(); i++) {
                if (!exist) {
                    System.err.println("您输入的编号不存在!请核对信息后重新输入~");
                    break;
                }
                System.out.println("请输入您要购买的数量(斤):");
                int num = sc.nextInt();
                int index = service.getIndex(fruitNum);
                if (list.get(index).getInventory() > num) {
                    arr[index] = num;
                    System.out.println("继续添加请按<1>           提交订单请按<0>");
                    int choic = sc.nextInt();
                    if (choic == 0) {
                        count();
                        service.inventory(fruitNum, num, arr);
                        return;
                    } else if (choic == 1) {
                        break;
                    }
                } else {
                    System.err.println("抱歉,库存不足,您可继续挑选其它商品~");
                    System.out.println("继续添加请按<1>                    返回上级菜单请按<0>");
                    int choic = sc.nextInt();
                    if (choic == 1) {
                        break;
                    } else if (choic == 0) {
                        return;
                    }
                }
            }
        }
    }
*/
   /* public void count() {
        int count = 0;
        for (int i = 0; i < list.size(); i++) {
            count += service.count(list.get(i).getName(), arr[i]);
        }
        System.out.print("您购买的水果原始总金额是:" + count + "元.");
        if (count <= 100) {
            System.out.println("您购买的水果原始总金额是:" + count + "元.");
        } else if (count > 100 && count <= 200) {
            count = (int) (100 + (count - 100) * 0.9);
            System.out.println("优惠之后的总金额是:" + count + "元");
        } else if (count <= 500) {
            count = (int) (200 * 0.9 + (count - 200) * 0.8);
            System.out.println("优惠之后的总金额是:" + count + "元");
        } else if (count > 500) {
            count = (int) ((200 * 0.9 + 300 * 0.8) + (count - 500) * 0.7);
            System.out.println("优惠之后的总金额是:" + count + "元");
        }
    }
*/
    public Socket getSocket() {
        //本质上相当于Map集合,getString方法相当于通过键去找值
        ResourceBundle rb = ResourceBundle.getBundle("prop");
        try {
            //这样设计的好处在于未来IP地址可以修改,使得客户端和服务器端不一定要运行在同一台电脑上
            return new Socket(rb.getString("ip"), Integer.parseInt(rb.getString("port")));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
